package com.example.goodskilldemo.controller;


import com.example.goodskilldemo.constants.Constants;
import com.example.goodskilldemo.http.Result;
import com.example.goodskilldemo.http.ResultGenerator;
import com.example.goodskilldemo.model.GoodsSeckill;
import com.example.goodskilldemo.service.IGoodsSeckillService;
import com.example.goodskilldemo.utils.MD5Utils;
import com.example.goodskilldemo.utils.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/seckill")
@Api(value = "GoodsSeckillController")
public class GoodsSeckillController {

    @Autowired
    private IGoodsSeckillService goodsSeckillService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 秒杀商品预热
     */
    @PostMapping("/hot")
    @ApiOperation("秒杀商品预热")
    public Result save(@RequestBody GoodsSeckill goodsSeckill) {
        if (goodsSeckill == null || goodsSeckill.getGoodsId() < 1 || goodsSeckill.getSeckillNum() < 1 || goodsSeckill.getSeckillPrice() < 1) {
            return ResultGenerator.genFailResult("参数异常");
        }
        boolean result = goodsSeckillService.save(goodsSeckill);
        if (result) {
            //虚拟预热
            redisCache.setCacheObject(Constants.SECKILL_GOODS_STOCK_KEY + goodsSeckill.getSeckillId(), goodsSeckill.getSeckillNum());
        }
        return ResultGenerator.genSuccessResult("数据预热成功");

    }

    @PostMapping("/hot/test")
    @ApiOperation("秒杀商品预热 在数据库加 【测试用】")
    public Result save2() {
        goodsSeckillService.hotData();
        return ResultGenerator.genSuccessResult("数据预热成功");

    }

    @GetMapping("/list")
    @ApiOperation("获取秒杀列表")
    public Result selectSeckillGoodsList() {

        return goodsSeckillService.selectSeckillGoodsList();
    }


    @PostMapping("/{seckillId}/exposer")
    @ApiOperation("获取秒杀链接")
    public Result exposerUrl(@PathVariable Long seckillId) {
        return goodsSeckillService.exposerUrl(seckillId);
    }


    @GetMapping("/{seckillId}")
    @ApiOperation("获取秒杀详情")
    public Result selectSeckillGoodDetail(@PathVariable Long seckillId) {
        return goodsSeckillService.selectSeckillGoodDetail(seckillId);
    }


    /**
     * 使用限流注解进行接口限流操作  --执行秒杀
     */
    @PostMapping("/seckillExcution/{seckillId}/{userId}/{md5}")
    @ApiOperation("执行秒杀")
    public Result execute(@PathVariable("seckillId") String seckillId,
                          @PathVariable("userId") String userId,
                          @PathVariable("md5") String md5) {

        //校验MD5
        if (StringUtils.isBlank(md5) || !md5.equals(MD5Utils.toMD5(seckillId))) {
            return ResultGenerator.genFailResult("秒杀商品不合法");
        }
        return goodsSeckillService.executeSeckill(Long.parseLong(seckillId), Long.parseLong(userId));
    }


}
